// 场景管理
controllers.controller('itemListCtrl', ['$scope', '$http', '$rootScope', '$modal', '$window', 'Item', 'AlertService', function ($scope, $http, $rootScope, $modal, $window, Item, AlertService) {
    $scope.resetCurrentPageName("商品维护");
    $scope.utils = Food.utils;
    $scope.pageSize = 20;
    $scope.currentPage = 1;
    $scope.itemList = Item.itemList;

    $scope.queryList = function () {
        Item.queryList($scope.currentPage, $scope.pageSize, $scope.title, $scope.userId, $scope.state, $scope.brandName, function () {
            $scope.totalItems = Item.totalSceneCount;
        });
    };
    $scope.downItem = function (itemId) {
        Item.downItem(itemId, function () {
            $scope.totalItems = Item.totalSceneCount;
        });
    };
    $scope.initUpdateItem = function (item) {

        Item.currentItem = item;
        $window.location.href = "#item/updateItem";

    };
    $scope.queryList();

    var operateTemplate = "<button class='btn btn-primary btn-sm' ng-click='grid.appScope.initUpdateItem(row.entity)'>修改</button>" +
        "<button class='btn btn-primary btn-sm' ng-click='grid.appScope.downItem(row.entity.id)'>下架</button>";

    $scope.gridOptions = {
        data: 'itemList',
        enableColumnMenus: false,
        enableColumnResizing: true,
        rowHeight: 100,
        columnDefs: [
            {
                field: 'id',
                displayName: 'id'
            },
            {
                field: 'title',
                displayName: '标题',
                cellTemplate: '<div>{{row.entity.title}}</div>'
            },
            {
                field: 'pic',
                displayName: '图片',
                width: "10%",
                cellTemplate: '<div class="ui-grid-cell-contents"><img src="{{row.entity.pic}}" style="width: 100px"/></div>'
            },
            {
                field: 'price',
                width: "15%",
                displayName: '价格',
                cellTemplate: '<div>原价：{{row.entity.price }}<br/> ' +
                'VIP价：{{row.entity.vipPrice}}<br/> ' +
                '佣金：{{row.entity.commission}}<br/> ' +
                '返现：{{row.entity.cashBack}}<br/> ' +
                '邮费：{{row.entity.postage}}</div>'
            },
            {
                field: 'itemDesc',
                displayName: '商品描述',
                cellTemplate: '<div>{{row.entity.itemDesc}}</div>'
            },
            {
                field: 'state',
                displayName: '商品状态',
                cellTemplate: '<div>{{row.entity.state == 0 ? "停用" :"在用"}}</div>'
            },
            {
                field: 'id',
                displayName: '操作',
                width: "10%",
                cellTemplate: operateTemplate
            }
        ]
    };
}]);

// 新增属性
controllers.controller('addItemCtrl', ['$scope', '$rootScope', '$modal', '$window', 'Item', 'Forest', 'AlertService',
    function ($scope, $rootScope, $modal, $window, Item, Forest, AlertService) {
        $scope.resetCurrentPageName("商品维护");
        $scope.currentItem = {};
        $scope.currentItem.descPicLists = [];
        $scope.rootCategory;
        $scope.childCategory;
        $scope.forestPropertyValueList = Forest.skuPropertyValueMap;
        $scope.otherPropertyValueMap = Forest.otherPropertyValueMap;
        $scope.skuList = [];
        $scope.miniSkuList = [];
        $scope.addImage = function () {
            //弹框选择属性，然后保存
            $scope._showAddImage(function () {
                //加入类目属性哦
                var picUrl = "";
                for (var index in $rootScope.selectedItemList) {
                    picUrl += $rootScope.selectedItemList[index].url
                }
                $scope.currentItem.pic = picUrl;
                $rootScope.modalIns.dismiss();
            });
        };

        $scope._showAddImage = function (callback) {
            $rootScope.contextIsModal = true;
            $rootScope.modalIns = $modal.open({
                templateUrl: './partials/image/imageList.html',
                animation: true,
                controller: 'imageListCtrl',
                windowClass: 'app-modal-window',
                size: 'lg',
                resolve: {}
            });
            $rootScope.ok = function () {
                callback();
            };
            $rootScope.cancel = function () {
                $rootScope.modalIns.dismiss();
            };
            $rootScope.modalIns.result.then(function () {
                $rootScope.contextIsModal = false;

            }, function () {
                $rootScope.contextIsModal = false;
            });
        }

        $scope.addOtherImage = function () {
            $scope._showAddImage(function () {
                //加入类目属性哦
                for (var index in $rootScope.selectedItemList) {
                    $scope.currentItem.descPicLists.push($rootScope.selectedItemList[index].url);
                }
                $rootScope.modalIns.dismiss();
            });
        };

        $scope.skuImageChange = function (position) {

            $scope._showAddImage(function () {
                //加入类目属性哦
                var picUrl = "";
                for (var index in $rootScope.selectedItemList) {
                    picUrl = $rootScope.selectedItemList[index].url
                }
                $scope.skuList[position].pic = picUrl;
                $rootScope.modalIns.dismiss();
            });
        }

        Forest.getForestTree(function () {
            $scope.rootForestList = Forest.rootForestList;
            $scope.childForestList = Forest.childForestList;
        });
        $scope.addItem = function () {
            $scope.miniSkuList = [];
            //把sku一起带过去
            for (var index in $scope.skuList) {
                var idArr = "";
                for (var i in $scope.skuList[index]) {
                    if ($scope.skuList[index][i]['id']) {
                        idArr += $scope.skuList[index][i]['id'] + ","
                    }
                }
                $scope.miniSkuList.push({
                    ids: idArr,
                    stock: $scope.skuList[index]['stock'],
                    //price: $scope.skuList[index]['price'],
                    //itemCode: $scope.skuList[index]['itemCode'],
                    pic: $scope.skuList[index]['pic']
                });
            }

            //描述图片解析
            $scope.currentItem.descPic = $scope.currentItem.descPicLists.toString();
            $scope.isAdding = true;
            Item.insert($scope.currentItem, $scope.miniSkuList, function () {
                AlertService.addAlert({type: 'success', msg: '商品新增成功了! '}, 1000);
                $window.location.href = "#item/itemList";
            }, function () {
                $scope.isAdding = false;
            });
        };

        $scope.rootCategoryChange = function (rootCategoryId) {
            $scope.rootCategory = rootCategoryId;
        }

        $scope.childCategoryChange = function (childCategoryId) {
            $scope.childCategory = childCategoryId;
            $scope.currentItem.categoryId = childCategoryId;
            //获取类目属性列表
            Forest.queryForestPropertyValue($scope.childCategory);
        }

        $scope.skuStockChange = function () {

            $scope.currentItem.stock = 0;
            for (var index in $scope.skuList) {
                if (parseInt($scope.skuList[index].stock)) {
                    $scope.currentItem.stock += parseInt($scope.skuList[index].stock);
                }
            }
        }

        $scope.skuChange = function (key, index) {
            $scope.forestPropertyValueList[key][index].choose = !$scope.forestPropertyValueList[key][index].choose;

            var arr = [];
            $.each($scope.forestPropertyValueList, function (key, value) {
                var properValueList = [];
                for (var index in value) {
                    if (value[index].choose) {
                        properValueList.push(value[index]);
                    }
                }
                if (properValueList.length == 0) {
                    properValueList.push({'value': '请选择'});
                }
                arr.push(properValueList);
            });
            $scope.skuList = $scope.descartes(arr);

        };
        $scope.otherPropertyChange = function (key, index) {
            $scope.otherPropertyValueMap[key][index].choose = !$scope.otherPropertyValueMap[key][index].choose;
            var feature = ""
            $.each($scope.otherPropertyValueMap, function (key, value) {
                var properValueList = [];
                for (var index in value) {
                    if (value[index].choose) {
                        feature += value[index]['propertyMetaId'] + ":" + value[index]['id'] + ","
                    }
                }
            });
            $scope.currentItem.feature = feature;

        }

        //笛卡儿积组合
        $scope.descartes = function descartes(list) {
            //parent上一级索引;count指针计数
            var point = {};
            var result = [];
            var pIndex = null;
            var tempCount = 0;
            var temp = [];
            //根据参数列生成指针对象
            for (var index in list) {
                if (typeof list[index] == 'object') {
                    point[index] = {'parent': pIndex, 'count': 0}
                    pIndex = index;
                }
            }
            //单维度数据结构直接返回
            if (pIndex == null) {
                return list;
            }
            //动态生成笛卡尔积
            while (true) {
                for (var index in list) {
                    tempCount = point[index]['count'];
                    temp.push(list[index][tempCount]);
                }
                //压入结果数组
                result.push(temp);
                temp = [];
                //检查指针最大值问题
                while (true) {
                    if (point[index]['count'] + 1 >= list[index].length) {
                        point[index]['count'] = 0;
                        pIndex = point[index]['parent'];
                        if (pIndex == null) {
                            return result;
                        }
                        //赋值parent进行再次检查
                        index = pIndex;
                    }
                    else {
                        point[index]['count']++;
                        break;
                    }
                }
            }
        }


    }]);

// 更新商品
controllers.controller('updateItemCtrl', ['$scope', '$rootScope', '$window', '$modal', 'Item', 'Forest', 'AlertService',
    function ($scope, $rootScope, $window, $modal, Item, Forest, AlertService) {
        $scope.resetCurrentPageName("商品维护");
        $scope.currentItem = Item.currentItem;
        $scope.rootCategory;
        $scope.childCategory;
        $scope.skuList;
        $scope.forestPropertyValueList = {};
        $scope.skuList = [];
        $scope.miniSkuList = [];

        $scope.addImage = function () {
            //弹框选择属性，然后保存
            $scope._showAddImage(function () {
                //加入类目属性哦
                var picUrl = "";
                for (var index in $rootScope.selectedItemList) {
                    picUrl += $rootScope.selectedItemList[index].url
                }
                $scope.currentItem.pic = picUrl;
                $rootScope.modalIns.dismiss();
            });
        };

        $scope._showAddImage = function (callback) {
            $rootScope.contextIsModal = true;
            $rootScope.modalIns = $modal.open({
                templateUrl: './partials/image/imageList.html',
                animation: true,
                controller: 'imageListCtrl',
                windowClass: 'app-modal-window',
                size: 'lg',
                resolve: {}
            });
            $rootScope.ok = function () {
                callback();
            };
            $rootScope.cancel = function () {
                $rootScope.modalIns.dismiss();
            };
            $rootScope.modalIns.result.then(function () {
                $rootScope.contextIsModal = false;

            }, function () {
                $rootScope.contextIsModal = false;
            });
        }

        $scope.addOtherImage = function () {
            $scope._showAddImage(function () {
                //加入类目属性哦
                for (var index in $rootScope.selectedItemList) {
                    $scope.currentItem.descPicList.push($rootScope.selectedItemList[index].url);
                }
                $rootScope.modalIns.dismiss();
            });
        };

        $scope.skuImageChange = function (position) {

            $scope._showAddImage(function () {
                //加入类目属性哦
                var picUrl = "";
                for (var index in $rootScope.selectedItemList) {
                    picUrl = $rootScope.selectedItemList[index].url
                }
                $scope.skuList[position].pic = picUrl;
                $rootScope.modalIns.dismiss();
            });
        }

        Item.queryDetail($scope.currentItem.id, function () {
            $scope.skuList = $scope.currentItem.itemSkuDOList;
            //重新解析sku
            if ($scope.skuList.length > 0) {
                var inited = false;
                $.each($scope.skuList, function (key, value) {
                    //这里可以sort吗？
                    if (!inited) {
                        $.each(value.propertyValueDOList, function (key, value1) {
                            $scope.forestPropertyValueList[value1.propertyMetaTitle] = {};
                        });
                        inited = true;
                    }
                    value.skuChild = [];
                    $.each(value.propertyValueDOList, function (key, value1) {
                        value.skuChild.push({'value': value1.value, 'propertyMetaTitle': value1.propertyMetaTitle});
                    });
                    value.skuChild;

                });
                $scope.skuList;
            }
            $scope.featureValueList = $scope.currentItem.featureValueDOList;
        });

        $scope.skuStockChange = function () {

            $scope.currentItem.stock = 0;
            for (var index in $scope.skuList) {
                if (parseInt($scope.skuList[index].stock)) {
                    $scope.currentItem.stock += parseInt($scope.skuList[index].stock);
                }
            }
        }


        $scope.updateItem = function () {

            $scope.currentItem.gmtCreate = new Date();
            $scope.currentItem.gmtModified = new Date();
            $scope.miniSkuList = [];
            //把sku一起带过去
            for (var index in $scope.skuList) {
                var idArr = $scope.skuList[index]['propertyValueIdArr'];
                $scope.miniSkuList.push({
                    ids: idArr,
                    stock: $scope.skuList[index]['stock'],
                    id: $scope.skuList[index]['id'],
                    itemId: $scope.skuList[index]['itemId'],
                    pic: $scope.skuList[index]['pic']
                });
            }
            //描述图片解析
            $scope.currentItem.descPic = $scope.currentItem.descPicList.toString();
            Item.update($scope.currentItem, $scope.miniSkuList, function () {
                AlertService.addAlert({type: 'success', msg: '商品更新成功了! '}, 1000);
                $window.location.href = "#item/itemList";
            });


        };

        $scope.skuStockChange = function () {

            $scope.currentItem.stock = 0;
            for (var index in $scope.skuList) {
                if (parseInt($scope.skuList[index].stock)) {
                    $scope.currentItem.stock += parseInt($scope.skuList[index].stock);
                }
            }
        }

    }]);

